package com.sbp.message.common;

import com.sbp.message.api.entity.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class RetryUtils implements InitializingBean {
    private final static Logger logger = LoggerFactory.getLogger(RetryUtils.class);

    @Value("${message.retryTime}")
    private String retryTimeStr;
    private int[] retryTimeArray;
    private int minElapseSeconds;
    public int getMinElapseSeconds() {
        return minElapseSeconds;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        try {
            String[] retryTimeStrArray = retryTimeStr.split(",");

            retryTimeArray = new int[retryTimeStrArray.length];
            for (int i = 0; i < retryTimeStrArray.length; ++i) {
                retryTimeArray[i] = Integer.parseInt(retryTimeStrArray[i]);
            }
        } catch (Exception e) {
            logger.warn("", e);

            retryTimeArray = new int[3];
            retryTimeArray[0] = 120;
            retryTimeArray[1] = 300;
            retryTimeArray[2] = 1800;
        }


        minElapseSeconds = retryTimeArray[0];
        for (int i=1; i<retryTimeArray.length; ++i) {
            if (minElapseSeconds > retryTimeArray[i])
                minElapseSeconds = retryTimeArray[i];
        }
    }



    /**
     * 判断 date1-date2 相差的秒数 是否 >= diffSeconds
     **/
    private static boolean dateComparison(long time1, long time2, int diffSeconds) {
        return time1 - time2 >= diffSeconds*1000;
    }

    public boolean isNeedRetry(Message message) {
        return message.getRetry() < retryTimeArray.length
                && dateComparison(System.currentTimeMillis(), message.getUpdateTime().getTime(), retryTimeArray[message.getRetry()]);
    }
    public boolean isDead(Message message) {
        // 超过最大重试次数 而且 上次更新时间距离当前时间>=6分钟, 更新消息状态为死亡
        return message.getRetry() >= retryTimeArray.length
                && dateComparison(System.currentTimeMillis(), message.getUpdateTime().getTime(), 360);
    }

}
